package com.tudouji.project.wechat.controller;

import com.tudouji.common.constant.HttpStatus;
import com.tudouji.common.utils.SecurityUtils;
import com.tudouji.common.utils.ServletUtils;
import com.tudouji.common.utils.spring.SpringUtils;
import com.tudouji.framework.aspectj.lang.annotation.Log;
import com.tudouji.framework.aspectj.lang.enums.BusinessType;
import com.tudouji.framework.config.EncrypAES;
import com.tudouji.framework.interceptor.annotation.RepeatSubmit;
import com.tudouji.framework.security.LoginUser;
import com.tudouji.framework.security.service.SysLoginService;
import com.tudouji.framework.security.service.TokenService;
import com.tudouji.framework.task.WhinfoRecordTask;
import com.tudouji.framework.web.controller.BaseController;
import com.tudouji.framework.web.domain.AjaxResult;
import com.tudouji.project.organization.domain.Supplier;
import com.tudouji.project.organization.mapper.SupplierMapper;
import com.tudouji.project.permission.service.IPermissiondefService;
import com.tudouji.project.system.domain.SysUser;
import com.tudouji.project.system.domain.Tuser;
import com.tudouji.project.system.service.ISysUserService;
import com.tudouji.project.system.service.ITuserService;
import com.tudouji.project.system.service.impl.SysUserServiceImpl;
import com.tudouji.project.wechat.config.WeixinCheckoutUtil;
import com.tudouji.project.wechat.service.impl.WechatServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import org.weixin4j.WeixinException;
import org.weixin4j.component.SnsComponent;
import org.weixin4j.model.sns.SnsAccessToken;
import org.weixin4j.spring.WeixinTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

/**
 * @author wf
 * @date 2021年05月26日 15:28
 */

@Slf4j
@Api(tags = {"微信模块"})
@RestController
@RequestMapping("/wechat")
public class WechatController extends BaseController {

    @Autowired
    private ISysUserService userService;
    @Autowired
    private ITuserService tuserService;

    @Autowired
    private WechatServiceImpl wechatService;


    @Autowired
    private WeixinTemplate weixinTemplate;

    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private IPermissiondefService permissiondefService;
    @Autowired
    private WhinfoRecordTask whinfoRecordTask;

    /**
     * 微信公众号签名认证接口
     *
     * @throws
     * @Title: test
     * @Description:
     * @param: @param signature
     * @param: @param timestamp
     * @param: @param nonce
     * @param: @param echostr
     * @param: @return
     * @return: String
     */
    @RepeatSubmit
    @RequestMapping("/auth")
    public String test(String signature, String timestamp, String nonce, String echostr) {
        log.info("----------auth token--------");
        // 通过检验signature对请求进行校验，若校验成功则原样返回echostr，表示接入成功，否则接入失败
        if (signature != null && WeixinCheckoutUtil.checkSignature(signature, timestamp, nonce)) {
            log.info("-----------auth success----------");
            return echostr;
        }
        return echostr;
    }

    @RepeatSubmit
    @ApiOperation(value = "通过code获取token", notes = "通过code获取token", httpMethod = "GET")
    @GetMapping("/getTokenByCode")
    public AjaxResult getTokenByCode(HttpServletResponse response, HttpServletRequest request, String code) {
        log.info("----------come here get token by code----------");

        String openid = (String) request.getSession().getAttribute("openid");

        log.info("--------get openid from session --------" + openid);

        log.info("------------get token by code-------" + code);
        SnsComponent snsComponent = weixinTemplate.sns();
        SnsAccessToken snsUser = null;
        try {
            if (StringUtils.isBlank(openid) && StringUtils.isNotBlank(code)) {
                snsUser = snsComponent.getSnsOAuth2AccessToken(code);
                openid = snsUser.getOpenid();
                log.info("--------------get openid by code  -----------" + openid);
            }
            if (StringUtils.isNotBlank(openid)) {
                log.info("----------set openid in session ----------");
                request.getSession().setAttribute("openid", openid);
                SysUser user = userService.selectUserByOpenid(openid);
                if (user != null) {
                    if (user.getStatus().equals("1")) {
//				        	throw new ApplicationException("user.blocked");//用户已禁用
                        return AjaxResult.error("用户已封禁，请联系管理员");
                    }
                    log.info("userName:"+user.getUserName()+",tuserid:"+user.getTuserId());
                    String token = wechatService.login(user.getUserName(), EncrypAES.decrypt(user.getPassword()), user);
                    log.info("----------from wx service token-------------" + token);
                    return AjaxResult.success(token);
                } else {
                    log.info("------------通过Openid未查找到用户----");
                    //通过openid未获取到用户
                    return AjaxResult.error(HttpStatus.UNAUTHORIZED, openid);
                }
            } else {
                //通过openid未获取到用户
                return AjaxResult.error(HttpStatus.UNAUTHORIZED, openid);
            }
        } catch (WeixinException e) {
            e.printStackTrace();
            return AjaxResult.error(HttpStatus.CLOSE_PAGE, "会话过期");
        }
    }

    @RepeatSubmit
    @ApiOperation(value = "微信登录", notes = "微信登录", httpMethod = "POST")
    @PostMapping("/wechatLogin")
    public AjaxResult wechatLogin(@RequestParam(required = true) String phone, @RequestParam(required = true) String pwd, HttpServletRequest request, String openid) {
        log.info("----------------前台参数---------" + openid);
        if (StringUtils.isBlank(openid)) {
            openid = (String) request.getSession().getAttribute("openid");
        }
//        if (StringUtils.isBlank(openid) && SecurityUtils.getLoginUser() != null) {
//            openid = SecurityUtils.getLoginUser().getUser().getOpenid();
//        }
        log.info("---------phone--------" + phone);
        log.info("----------------wechatlogin openid---------" + openid);
        return this.wechatService.wechatLogin(phone, pwd, openid, false);
    }

    @RepeatSubmit
    @ApiOperation(value = "短信验证码", notes = "短信验证码", httpMethod = "GET")
    @GetMapping("/getSmsCode")
    public AjaxResult getSmsCode(String phoneNumber) {
        log.info("------------phoneNumber--------"+phoneNumber);
        return this.wechatService.getSmsCode(phoneNumber);
    }

    @RepeatSubmit
    @ApiOperation(value = "微信注册", notes = "微信注册", httpMethod = "POST")
    @PostMapping("/wechatRegist")
    public AjaxResult wechatRegist(@RequestBody(required = true) SysUser user, @RequestParam String smsCode, String managerID) {
        AjaxResult result = wechatService.checkSmsCode(user.getPhonenumber(), smsCode);
        if ((Integer) result.get(AjaxResult.CODE_TAG) == HttpStatus.SUCCESS) {
            return this.wechatService.wechatRegist(user, managerID);
        } else {
            return result;
        }
    }

    /**
     * 重置密码
     */
    @RepeatSubmit
    @Log(title = "个人信息", businessType = BusinessType.UPDATE)
    @PostMapping("/updatePwd")
    public AjaxResult updatePwd(String phoneNumber, String newPassword, String smscode) {
        SysUser loginUser = userService.selectUserByUserName(phoneNumber);
        if (null == loginUser) {
            return AjaxResult.error("用户账户不存在");
        }
        AjaxResult result = wechatService.checkSmsCode(phoneNumber, smscode);
        if ((Integer) result.get(AjaxResult.CODE_TAG) != HttpStatus.SUCCESS) {
            return result;
        }
        if (userService.resetUserPwd(phoneNumber, SecurityUtils.encryptPassword(newPassword)) > 0) {
            return AjaxResult.success();
        }
        return AjaxResult.error("修改密码异常");
    }


    @GetMapping("/getUser")
    public AjaxResult getUser() {
        AjaxResult result = AjaxResult.success();
        Long userId = SecurityUtils.getLoginUser().getUser().getUserId();
        SysUser user = userService.selectUserById(userId);
        if ("1".equalsIgnoreCase(user.getUserType())){
            Supplier supplier = supplierMapper.selectSupplierByUserid(user.getGuid());
            if (null != supplier){
                user.setSupplier(supplier);
            }
        }
        return AjaxResult.success(user);
    }

    @GetMapping("getFuncs")
    public AjaxResult getFuncs(){
        String token = ServletUtils.getRequest().getHeader("Authorization");
        log.info("--------getFuncs: token----------" + token);
        log.info("--------getFuncs----------");
        return permissiondefService.getFuncs();
    }


    @GetMapping("rpt")
    public void getFuncs(Date date){
        whinfoRecordTask.rpt(date);
    }
}

